﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace StockLib.Data
{
    public class BaseFileLoader
    {
        public virtual List<BaseData> Load(Stock stock)
        {
            List<BaseData> baseData = new List<BaseData>();

            FileInfo fi = new FileInfo(StockData.Instance.GetFileName(stock, DataType.Base));
            if (!fi.Exists)
                return baseData;

            FileStream fs = null;
            StreamReader sr = null;
            try
            {
                fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                sr = new StreamReader(fs, System.Text.Encoding.Default);
                string pattern = string.Format(@"☆(.+)☆\s*◇(.+)更新日期：(.+)◇", stock.Code, stock.Name);
                StringBuilder text = new StringBuilder();
                BaseData data = null;
                bool matched = false;
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    Match match = Regex.Match(line, pattern);
                    if (match.Success)
                    {
                        if (text.Length > 0)
                        {
                            data.Content = text.ToString();
                            baseData.Add(data);
                            text.Remove(0, text.Length);
                        }
                        data = new BaseData();
                        data.Column = match.Groups[1].Value;
                        matched = true;
                    }
                    else
                    {
                        text.AppendLine(line);
                    }
                }
                if (matched && text.Length > 0)
                {
                    data.Content = text.ToString();
                    baseData.Add(data);
                    text.Remove(0, text.Length);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw ex;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }

            return baseData;
        }
    }
}
